﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.HtmlControls;

using OctoOS;
using OctoOS.UI;

using LinkButton = OctoOS.UI.LinkButton;
using TreeView = OctoOS.UI.TreeView;

public partial class __editArticle : OOSPage
{
	class PathInfo
	{
		[PathInfoMember(0, true)]
		[IntegerBase(64)]
		internal long ID = 0;
	}

	PathInfo _pathInfo;
	Article _article;
	bool _articleEnabled = false;
	Category[] _categories;

	protected void Page_Init(object sender, EventArgs e)
	{
		OOSRequest.Current.EnsureSignIn();

		_pathInfo = EnablePathInfo<PathInfo>();
		_categories = AppUtil.GetCategories(OOSRequest.Current);

		foreach(var category in _categories)
		{
			categories1.Items.Add(new Option() { Text = category.Title, Value = category.CategoryID.ToString() });
			categories2.Items.Add(new Option() { Text = category.Title, Value = category.CategoryID.ToString() });
			categories3.Items.Add(new Option() { Text = category.Title, Value = category.CategoryID.ToString() });
		}

		if(_pathInfo.ID != 0)
		{
			_article = ApiService.GetArticle(OOSRequest.Current, _pathInfo.ID);
			if(_article == null)
				throw new HttpException(404, "Article Not Found");

			if(!OOSRequest.Current.IsModerator &&
				_article.UserID != OOSRequest.Current.UserID)
			{
				throw new HttpException();
			}

			articleID.Value = _pathInfo.ID.ToString();
			_articleEnabled = _article.PublishStartTime < DateTime.MaxValue;

			if(_articleEnabled)
			{
				if(_article.PublishStartTime <= DateTime.UtcNow)
					publishStarted.Value = "true";

				startAtRadio.Checked = true;
				publishStartDate.Value = _article.PublishStartTime;
			}

			if(_article.PublishStopTime < DateTime.MaxValue)
			{
				stopAtRadio.Checked = true;
				publishStopDate.Value = _article.PublishStopTime;
			}

			if(_article.PublishStopTime < DateTime.UtcNow)
				publishStopped.Value = "true";
		}
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		savedMsg.SetContent(Resources.Main.editArticle_SavedMessage);

		AddBreadcrumb(string.Empty, "/");
		AddBreadcrumb(Resources.Main.shared_MyArticlesLink, Urls.GetMyArticles());
		SetServiceLinks();

		if(_pathInfo.ID == 0)
		{
			PageTitle = Resources.Main.editArticle_AddTitle;
		}
		else
		{
			PageTitle = Resources.Main.editArticle_EditTitle;
			Commands.AddCommand(Resources.Main.shared_ViewArticle, Urls.GetArticle(_pathInfo.ID, true, false, _article.Title));
			Commands.AddCommand(Resources.Main.editArticle_AddPage, Urls.GetAddPage(_pathInfo.ID));
			Commands.AddCommand(Resources.Main.editArticle_DeleteArticle, Urls.GetDeleteArticle(_pathInfo.ID));

			for(int i = 0; i < _article.CategoryIDs.Length; i++)
			{
				long categoryID = _article.CategoryIDs[i];

				var currentCategory = AppUtil.GetCategory(_categories, categoryID);

				if(i == 0)
				{
					categories1.SelectedValue = currentCategory.CategoryID.ToString();
					featured1.Checked = currentCategory.Featured(categoryID);
				}
				else if(i == 1)
				{
					categories2.SelectedValue = currentCategory.CategoryID.ToString();
                    featured2.Checked = currentCategory.Featured(categoryID);
				}
				else
				{
					categories3.SelectedValue = currentCategory.CategoryID.ToString();
                    featured3.Checked = currentCategory.Featured(categoryID);
				}
			}

			if(!IsPostBack)
			{
				author.Text = _article.Author;
				title.Text = _article.Title;
				preface.Text = _article.Preface;
				publishedSelect.SelectedValue = _articleEnabled.ToString().ToLower();
			}
			
			foreach(var page in _article.GetPages(true))
				ShowPage(page);
		}
	}

	private void SetServiceLinks()
	{
		ajaxSectionsServiceUrl.Text = OOSRequest.Current.GetContextPath("/") +
			Urls.Ajax.GetSaveSectionsOrder();
		ajaxPagesServiceUrl.Text = OOSRequest.Current.GetContextPath("/") +
			Urls.Ajax.GetSavePagesOrder();
		deleteSectionUrl.Text = OOSRequest.Current.GetContextPath("/") +
			Urls.Ajax.GetDeleteSection();
		deletePageUrl.Text = OOSRequest.Current.GetContextPath("/") +
			Urls.Ajax.GetDeletePage();
	}

	protected void SubmitClick(object sender, EventArgs e)
	{
		if(IsValid)
		{
			bool published = Convert.ToBoolean(publishedSelect.SelectedValue);

			DateTime publishStartTime = DateTime.MaxValue;
			if(published)
			{
				if(_article != null && _article.PublishedNow)
				{
					publishStartTime = _article.PublishStartTime;
				}
				else
				{
					if(startAtRadio.Checked)
						publishStartTime = publishStartDate.Value;
					else
						publishStartTime = DateTime.UtcNow;
				}
			}

			DateTime publishStopTime = DateTime.MaxValue;
			if(published)
			{
				if(stopAtRadio.Checked)
					publishStopTime = publishStopDate.Value;
			}


			if(_pathInfo.ID == 0)
			{
				ApiService.InsertArticle(OOSRequest.Current, author.TrimmedText,
					title.TrimmedText, preface.TrimmedText, publishStartTime,
					publishStopTime, GetSelectedCategoryIDs());

				Response.Redirect(Urls.GetEditArticle(OOSRequest.Current.RequestID));
			}
			else
			{
				ApiService.UpdateArticle(OOSRequest.Current, _pathInfo.ID,
					author.TrimmedText, title.TrimmedText, preface.TrimmedText,
					publishStartTime, publishStopTime, GetSelectedCategoryIDs());

				Response.Redirect(Urls.GetEditArticle(_pathInfo.ID));
			}
		}
	}


	protected void CategoriesValidate(object sender, ValidateEventArgs e)
	{
		//должна быть выбрана хотя бы 1 категория
		if(categories1.SelectedValue == "0"
			&& categories2.SelectedValue == "0"
			&& categories3.SelectedValue == "0")
		{
			e.ErrorMessage = Resources.Main.editArticle_SelectCategoryWarning;
		}
		else
		{
			List<string> categoryIDs = new List<string>();

			if(categories1.SelectedValue != "0")
				categoryIDs.Add(categories1.SelectedValue);

			if(categories2.SelectedValue != "0")
			{
				if(categoryIDs.Contains(categories2.SelectedValue))
					e.ErrorMessage = Resources.Main.editArticle_CategoryWarning;
				else
					categoryIDs.Add(categories2.SelectedValue);
			}

			if(categories3.SelectedValue != "0")
			{
				if(categoryIDs.Contains(categories3.SelectedValue))
					e.ErrorMessage = Resources.Main.editArticle_CategoryWarning;
				else
					categoryIDs.Add(categories3.SelectedValue);
			}
		}
	}

	/// <summary>
	/// Returns CategoryID/Featured dictionary
	/// </summary>
	/// <param name="published"></param>
	/// <returns></returns>
	private Dictionary<long, bool> GetSelectedCategoryIDs()
	{
		Dictionary<long, bool> selectedCategories = new Dictionary<long, bool>();

		long categoryID1 = Convert.ToInt64(categories1.SelectedValue);
		if(categoryID1 > 0)
			selectedCategories.Add(categoryID1, featured1.Checked);

		long categoryID2 = Convert.ToInt64(categories2.SelectedValue);
		if(categoryID2 > 0)
			selectedCategories.Add(categoryID2, featured2.Checked);

		long categoryID3 = Convert.ToInt64(categories3.SelectedValue);
		if(categoryID3 > 0)
			selectedCategories.Add(categoryID3, featured3.Checked);


		//List<long> categoryIDs = new List<long>();

		//long categoryID1 = Convert.ToInt64(categories1.SelectedValue);
		

		//if(categoryID1 > 0)
		//{
		//	var currentCategory = AppUtil.GetCategory(_categories, categoryID1);
		//	if(currentCategory == null)
		//		throw new ApplicationException();

		//	var articleCategoryID = currentCategory.GetArticleCategoryID(featured1.Checked, published);
		//	categoryIDs.Add(articleCategoryID);
		//}

		//long categoryID2 = Convert.ToInt64(categories2.SelectedValue);
		//if(categoryID2 > 0)
		//{
		//	var currentCategory = AppUtil.GetCategory(_categories, categoryID2);
		//	if(currentCategory == null)
		//		throw new ApplicationException();

		//	var articleCategoryID = currentCategory.GetArticleCategoryID(featured2.Checked, published);
		//	categoryIDs.Add(articleCategoryID);
		//}

		//long categoryID3 = Convert.ToInt64(categories3.SelectedValue);
		//if(categoryID3 > 0)
		//{
		//	var currentCategory = AppUtil.GetCategory(_categories, categoryID3);
		//	if(currentCategory == null)
		//		throw new ApplicationException();

		//	var articleCategoryID = currentCategory.GetArticleCategoryID(featured3.Checked, published);
		//	categoryIDs.Add(articleCategoryID);
		//}

		return selectedCategories;
	}

	private void ShowPage(Page page)
	{
		HtmlGenericControl pageDiv = new HtmlGenericControl("div");
		pageDiv.Attributes.Add("id", page.ID.ToString());
		pageDiv.Attributes.Add("style", "border:1px solid black; margin-bottom:5px;");

		pageDiv.Controls.Add(new LinkButton
		{
			Text = Resources.Main.editArticle_AddSection,
			CssClass = "actionButton",
			HRef = Urls.GetAddSection(_pathInfo.ID, page.ID)
		});

		//add page tree node
		TreeView pageTreeView = new TreeView();
		PageUIPreview pagePreview = new PageUIPreview(_pathInfo.ID, page);
		var pageNode = pageTreeView.Nodes.AddContentNode(pagePreview);

		foreach(var section in page.Sections)
		{
			var sectionPreview = 
				new SectionUIPreview(_pathInfo.ID, page.ID, section, _article.Title);

			ContentTreeNode sectionNode = new ContentTreeNode(sectionPreview)
			{
				ID = page.ID + "_" + section.ID
			};

			pageNode.Nodes.Add(sectionNode);
		}
		pageDiv.Controls.Add(pageTreeView);
		pagesPlaceholder.Controls.Add(pageDiv);
	}

	protected void PublishStartDateValidate(object sender, ValidateEventArgs e)
	{
		if(startAtRadio.Checked)
		{
			if(String.IsNullOrEmpty(publishStartDate.TrimmedText))
				e.ErrorMessage = Resources.Main.editArticle_EmptyField;
		}
	}

	protected void PublishStopDateValidate(object sender, ValidateEventArgs e)
	{
		if(publishedSelect.SelectedValue == "true")
		{
			if(stopAtRadio.Checked)
			{
				if(String.IsNullOrEmpty(publishStopDate.TrimmedText))
				{
					e.ErrorMessage = Resources.Main.editArticle_EmptyField;
					return;
				}

				var stopDate = publishStopDate.Value;

				if(startNowRadio.Checked)
				{
					if(stopDate <= DateTime.UtcNow.Date)
						e.ErrorMessage = Resources.Main.editArticle_StopPublishingWarning;
				}
				else
				{
					if(_articleEnabled)
					{
						if(stopDate < _article.PublishStartTime)
							e.ErrorMessage = Resources.Main.editArticle_StopPublishingWarning;
					}
					else
					{
						if(stopDate <= publishStartDate.Value.Date)
							e.ErrorMessage = Resources.Main.editArticle_StopPublishingWarning;
					}
				}
			}
		}
	}
}